package com.luzhikun.dynameRegist;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.util.EnumSet;

/**
 * @Author Rookie Coder
 * @Description 动态注册Servlet、Filter、request三大组件
 * @Date
 **/
@WebListener
public class MyServletContextListener implements ServletContextListener {
/*
 * @Author liu-miss
 * @Description Context初始化的时候触发该方法
 * @Date 22:27 2021/5/6
 **/
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        // 获取ServletContext上下文对象
        ServletContext sc = sce.getServletContext();
        //---------------------- 动态注册Servlet-------------------------------
        // 下面两个变量一般是通过配置文件读取出来的
        String servletName="SomeServlet";
        String className="com.luzhikun.dynameRegist.SomeServlet";

        ServletRegistration.Dynamic dynamic = sc.addServlet(servletName, className);
        dynamic.setInitParameter("username","吴杰");
        dynamic.setInitParameter("baichi","傻逼");

        // 给动态注册的Servlet类注册url-patten
        dynamic.addMapping("/some");


        //---------------------- 动态注册Filter-------------------------------
        // 下面两个变量一般是通过配置文件读取出来的
        String name="SomeFilter";
        String filterClassName="com.luzhikun.dynameRegist.SomeFilter";
        FilterRegistration.Dynamic dynamic1 = sc.addFilter( name, filterClassName);
//        // 配置当前Filter的映射信息
        dynamic1.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");

        //---------------------- 动态注册Listener-------------------------------
        // 下面两个变量一般是通过配置文件读取出来的
        String listenerClassName="com.luzhikun.dynameRegist.MyRequestListener";
        sc.addListener(listenerClassName);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
